import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../pages/web_page.dart';
import '../extentions/build_context_extentions.dart';
import 'logger.dart';

class HttpLogDetailPage extends StatefulWidget {
  final HttpLog log;

  const HttpLogDetailPage({Key? key, required this.log}) : super(key: key);

  @override
  _HttpLogDetailPageState createState() => _HttpLogDetailPageState();
}

class _HttpLogDetailPageState extends State<HttpLogDetailPage> {
  static const text14_yellow =
      const TextStyle(color: const Color(0xFFFA8C16), fontSize: 14);
  static const text14_25 =
      const TextStyle(color: const Color(0xff252525), fontSize: 14);
  static const text14_99 =
      const TextStyle(color: const Color(0xff999999), fontSize: 14);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.log.summary?.title ?? widget.log.url!),
        centerTitle: true,
        actions: [
          Builder(
            builder: (context) => InkWell(
              onTap: () {
                Clipboard.setData(ClipboardData(text: widget.log.curl));
                context.showSnackBar("已复制到剪贴板");
              },
              child: Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 15),
                  child: Text('复制curl')),
            ),
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Headers', style: text14_yellow),
              Column(
                children: widget.log.headers!.entries
                    .map((e) => Padding(
                          padding: const EdgeInsets.only(top: 5),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text('${e.key}:  ', style: text14_25),
                              Expanded(
                                  child:
                                      Text(e.value ?? 'null', style: text14_99))
                            ],
                          ),
                        ))
                    .toList(),
              ),
              SizedBox(height: 10),
              Text('Params', style: text14_yellow),
              widget.log.params!.isEmpty
                  ? (widget.log.body == null
                      ? Text(widget.log.params.toString())
                      : SingleChildScrollView(
                          scrollDirection: Axis.horizontal,
                          child: Text(
                            _formatMapToJsonString(widget.log.body!),
                          ),
                        ))
                  : Column(
                      children: widget.log.params!.entries
                          .map((e) => Padding(
                                padding: const EdgeInsets.only(top: 5),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text('${e.key}:  ', style: text14_25),
                                    Expanded(
                                        child: Text(e.value ?? 'null',
                                            style: text14_99))
                                  ],
                                ),
                              ))
                          .toList(),
                    ),
              SizedBox(height: 10),
              Text('耗时', style: text14_yellow),
              SizedBox(height: 5),
              Text('${widget.log.totalTime}ms'),
              SizedBox(height: 10),
              if (widget.log.isSuccess) ...[
                Row(
                  children: [
                    Text('Response', style: text14_yellow),
                    Builder(
                      builder: (BuildContext context) {
                        return IconButton(
                            icon: Icon(Icons.copy_rounded),
                            onPressed: () {
                              Clipboard.setData(ClipboardData(
                                text: _formatMapToJsonString(
                                    widget.log.response!),
                              ));
                              context.showSnackBar("已复制到剪贴板");
                            });
                      },
                    ),
                  ],
                ),
                SizedBox(height: 5),
                SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: Text(
                    _formatMapToJsonString(widget.log.response!),
                    style: TextStyle(fontSize: 15, color: Colors.black),
                  ),
                ),
              ],
            ],
          ),
        ),
      ),
      floatingActionButton: widget.log.summary == null
          ? null
          : FloatingActionButton(
              child: Text("doc"),
              onPressed: () {
                showDocPage(context);
              },
            ),
    );
  }

  void showDocPage(BuildContext context) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => WebPage(
          url: widget.log.summary!.docUrl,
          titleText: widget.log.summary!.title,
        ),
      ),
    );
  }

  String _formatMapToJsonString(Map<String, dynamic> map) {
    String jsonString = "";
    jsonString += "{\n";
    jsonString += _parseMap(map, 1);
    jsonString += "}";
    return jsonString;
  }

  String _parseMap(Map<String, dynamic> map, int level) {
    String str = "";
    map.entries.forEach((e) {
      str += "".padLeft(8 * level);
      if (e.value is Map) {
        str += '"${e.key}":  {\n';
        str += _parseMap(e.value, level + 1);
        str += "".padLeft(8 * level);
        str += '},';
      } else if (e.value is List) {
        str += '"${e.key}":  [\n';
        str += _parseListItem(e.value, level + 1);
        str += "".padLeft(8 * level);
        str += '],';
      } else {
        str += '"${e.key}":  ${e.value is String ? '"${e.value}"' : e.value},';
      }
      str += '\n';
    });
    return str;
  }

  String _parseListItem(List<dynamic> list, int level) {
    String str = "";
    list.forEach((e) {
      str += "".padLeft(8 * level);
      if (e is Map) {
        str += "{\n";
        str += _parseMap(e as Map<String, dynamic>, level + 1);
        str += "".padLeft(8 * level);
        str += '},';
      } else if (e is List) {
      } else {
        str += '${e is String ? '"$e"' : e},';
      }
      str += '\n';
    });
    return str;
  }
}
